import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout/index.vue'
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
import store from '@/store'

const Login = () => import('@/views/login/index.vue')
const Search = () => import('@/views/search/index.vue')
const SearchList = () => import('@/views/search/list.vue')
const ProDetail = () => import('@/views/proDetail/index.vue')
const Pay = () => import('@/views/pay/index.vue')
const MyOrder = () => import('@/views/myOrder/index.vue')

// 使用VueRouter插件扩展Vue的功能
Vue.use(VueRouter)

// 创建 VueRouter 实例，配置路由规则
const router = new VueRouter({
  routes: [
    // 登录页面路由
    { path: '/login', component: Login },
    // 根路由，重定向到首页，并包含子路由
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        // 首页路由
        { path: '/home', component: Home },
        // 分类页面路由
        { path: '/category', component: Category },
        // 购物车页面路由
        { path: '/cart', component: Cart },
        // 用户中心页面路由
        { path: '/user', component: User }
      ]
    },
    // 搜索页面路由
    { path: '/search', component: Search },
    // 搜索列表页面路由
    { path: '/searchList', component: SearchList },
    // 动态路由传参，确认具体商品, 路由参数中携带id
    { path: '/proDetail/:id', component: ProDetail },
    // 支付页面路由
    { path: '/pay', component: Pay },
    // 我的订单页面路由
    { path: '/myOrder', component: MyOrder }
  ]
})

// 全局前置导航守卫
// to: 到哪里去，要提供完整的路由信息对象（路径，参数）
// from: 从哪里来，提供完整的路由信息对象（路径，参数）
// next(): 是否放行
// (1) next() 直接放行到 to 定义的路径
// (2) next(路径) 进行拦截，跳转到 next 中配置的路径

// 定义一个数组，专门存放用户所有需要权限访问的页面
const authUrls = ['/pay', '/myOrder']

router.beforeEach((to, from, next) => {
  // 判断是否为权限页面
  if (!authUrls.includes(to.path)) {
    // 不是权限页面
    next()
    return
  }
  // 是权限页面，需要判断 token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
